<?php
/**
 * 名称：PushAction
 * 描述：后台推送管理
 * 作者：sun 时间：2013-12-05
 * 版本号：V1.0.0
 * ========================历史版本=================================
 * 序号	 版本号 	日期			姓名	 	描述
 * 1 	V1.0.0 	2013-12-05 	sun  	后台推送管理
 * ========================历史版本=================================
 * 说明：请在有更改程序的时候修改以上注释
 */
class PushAction extends CommonAction {
	/**
	 * 推送配置
	 */
	public function pushConfig(){
		$pushConfig = include SITE_PATH . '/apps/admin/Conf/pushConfig.php';
		$this->assign("push",$pushConfig);
		$this->display();
	}
	
	/**
	 * 推送配置
	 */
	public function dopushConfig(){
		try {
			$filename = SITE_PATH . '/apps/admin/Conf/pushConfig.php';
			file_exists($filename) or touch($filename);
			if($_POST['__hash__']) unset($_POST['__hash__']);
			if($_POST['configname']) unset($_POST['configname']);
			$return = var_export($_POST, TRUE);
			if ($return) {
				file_put_contents($filename, "<?php \r\n return " . $return . ";");
			}
			$this->success('配置成功');
		} catch (Exception $e) {
			$this->error("请检查文件{$filename}是否有读写权限");
		}
	}
	
	/**
	 * 系统级推送
	 */
	public function syspush(){
		$role = M ( 'Role' );
		$list = $role->order ( 'id' )->select ();
		$this->assign ( 'list', $list );
		$this->display();
	}

	/**
	 * 应用级推送
	 */
	public function apppush(){
		$articleId = $_GET['ids'];
		if(!empty($articleId)){
			$domain = M('cms_site') -> where("siteid = ".$_GET['sid']) ->getField("domain");
			if( strpos(trim($domain),"/") === 0){
				$domain = 'http://'.SITE_DOMAIN.$domain;
			}
			if(strrpos(trim($domain),"/") !== (strlen(trim($domain))-1)){
				$domain = $domain.'/';
			}
			$artnaming = M('cms_category') -> where('id='.$_GET['cid']) ->getField('artnaming');
			if(empty($artnaming)){
				$artarr =  model('Data')->get('cmsconfig:site-'.$_GET['sid']);
				$artnaming = $artarr["artnaming"];
			}
			$article = M('cms_article') -> where("`status`=1 and `id` in(".$articleId.")") -> field("id,title,url,imageurl,description") -> select();
			$search_str_citeid = array("{cateid}","{@ChannelID}");
			$search_str_contentid = array("{contentid}","{@ContentID}");
			foreach ($article as $k => $v){
				$artlist[$k]["title"] = $v["title"];
				if(empty($v["url"])){
					$artnaming_temp = str_replace($search_str_citeid,$_GET['cid'],$artnaming);
					$artlist[$k]["url"] = $domain.str_replace($search_str_contentid,$v["id"],$artnaming_temp);
				}else {
					$artlist[$k]["url"] = $v["url"];
				}
				$body .= $artlist[$k]["title"].$artlist[$k]["url"]."\n";
				
			}
			
			$this->assign('content',$body);
		}
		
		$role = M ( 'Role' );
		$list = $role->order ( 'id' )->select ();
		$this->assign ( 'list', $list );
		$this->display();
	}
	
	/**
	 * 开始系统级推送
	 */
	public function dosyspush(){
		if(empty($_POST['title'])){
			echo "标题不能为空";
			exit;
		}
		if(empty($_POST['content'])){
			echo "内容不能为空";
			exit;
		}
		if(empty($_POST['userlist'])){
			$res = $this->getUserId();
		}else {
			$res = $_POST['userlist'];
		}
		
		$pushConfig = include SITE_PATH . '/apps/admin/Conf/pushConfig.php';
		$data['appid'] = $pushConfig['appid'];
		if(empty($res['pushid'])){
			$data['to'] = implode('|',$res);
			$data['pushid'] = uniqid();
		}else{
			$data['pushid'] = $res['pushid'];
		}
		$data['title'] = $_POST['title'];
		$data['body'] = $_POST['content'];
		$data['count'] = 1;
		$data['stamp'] = date("YmdHis",time());
		$data['sign'] = md5(implode('',$data));
		$data = @http_build_query($data);  //把参数转换成URL数据
		$aContext = array('http' => array('method' => 'POST',
				'header'  => 'Content-type: application/x-www-form-urlencoded',
				'content' => $data ));
		$cxContext  = stream_context_create($aContext);
		$sUrl = $pushConfig['syspush']; //此处必须为完整路径
		$fgcres = @file_get_contents($sUrl,false,$cxContext);
		$r = json_decode($fgcres,true);
		if(intval($r["code"]) === 0){
			echo $r['msg'];
		}else{
			if(!empty($res['pushid'])){
				include_once( "./apps/weibo/Lib/Action/PushMAction.class.php" );
				$pusha = new PushMAction();
				$pusha -> remove($res);
			}
			echo $r["code"].$r['msg'];
		}
	}
	
	/**
	 * 开始应用级推送
	 */
	public function doapppush(){
		if(empty($_POST['content'])){
			echo "内容不能为空";
			exit;
		}
		if(empty($_POST['userlist'])){
			$res = $this->getUserId();
		}else {
			$res = $_POST['userlist'];
		}
		$pushConfig = include SITE_PATH . '/apps/admin/Conf/pushConfig.php';
		$data['appid'] = $pushConfig['appid'];
		if(empty($res['pushid'])){
			$data['to'] = implode('|',$res);
			$data['pushid'] = uniqid();
		}else{
			$data['pushid'] = $res['pushid'];
		}
		$data['type'] = 1;
		$data['content'] = $_POST['content'];
		$data['count'] = 1;
		$data['stamp'] = date("YmdHis",time());
		
		$data['sign'] = md5(implode('',$data));
		
		
		$data = @http_build_query($data);  //把参数转换成URL数据
		$aContext = array('http' => array('method' => 'GET',
				'header'  => 'Content-type: application/x-www-form-urlencoded',
				'content' => $data ));
		$cxContext  = stream_context_create($aContext);
		
		$sUrl = $pushConfig['apppush']; //此处必须为完整路径
		$fgcres = @file_get_contents($sUrl,false,$cxContext);
		
		$r = json_decode($fgcres,true);
		if(intval($r["code"]) === 0){
			echo $r['msg'];
		}else{
			if(!empty($res['pushid'])){
				include_once( "./apps/weibo/Lib/Action/PushMAction.class.php" );
				$pusha = new PushMAction();
				$pusha -> remove($res);
			}
			echo $r['msg'];
		}
	}
	
	/**
	 * 获取推送用户id
	 * 
	 * 推送用户数量小于50，返回用户id数组 
	 * 
	 * 推送用户数量大于50，返回唯一pushid，并往mongodb push表更新数据
	 */
	private function getUserId(){
		$id = intval ( $_POST ['id'] );
		$type = intval ( $_POST ['type'] );
		$ru = M ( 'RoleUser' );
		$user = M ( 'User' );
		
		// 如果id=0，表示所有用户,获取所有用户的uid
		if ($id == 0) {
			$data ['is_active'] = array (
					'eq',
					'1'
			);
			$list = $user->where ( $data )->field ( 'uid' )->order ( 'uid' )->select ();
			$count = $user->where($data)->field('uid')->order('uid')->count();
		} else {
			$count = $ru->where ( "role_id=$id" )->count ();
			$list = $ru->where ( "role_id=$id" )->field('user_id as uid')->select ();
		}
		foreach ($list as $k => $v){
			$list[$k] = $v['uid'];
		}
		if($count < 50){
			return $list;
		}
		$pushid = uniqid();
		$pushdata = array("userid" => $list,"pushid" => $pushid);
		include_once( "./apps/weibo/Lib/Action/PushMAction.class.php" );
		$pusha = new PushMAction();
		$pusha -> add($pushdata);
		return $pushdata;
	}
	
}

?>